<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="退款编号" prop="refundNumber">
        <el-input
          v-model="queryParams.refundNumber"
          placeholder="请输入退款编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="退款类型" prop="refundType">
        <el-select v-model="queryParams.refundType" placeholder="请选择退款类型" clearable>
          <el-option label="全部" value="" />
          <el-option label="仅退款" value="refund" />
          <el-option label="退款退货" value="refund_return" />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间" prop="applicationTime">
        <el-date-picker
          v-model="queryParams.applicationTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">筛选</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 状态分类标签页 -->
    <div class="status-tabs">
      <el-tabs v-model="activeStatus" @tab-click="handleStatusChange">
        <el-tab-pane label="全部" name="all"></el-tab-pane>
        <el-tab-pane label="待处理" name="pending"></el-tab-pane>
        <el-tab-pane label="退货中" name="returning"></el-tab-pane>
        <el-tab-pane label="退款中" name="refunding"></el-tab-pane>
        <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
        <el-tab-pane label="已拒绝" name="rejected"></el-tab-pane>
        <el-tab-pane label="已退款" name="refunded"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tuikuanguanli:tuikuanguanli:export']"
        >EXCEL导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 退款记录表格 -->
    <el-table v-loading="loading" :data="refundList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品" align="center" width="300">
        <template slot-scope="scope">
          <div class="product-info">
            <div class="refund-info">
              <div class="refund-number">退款编号: {{ scope.row.id }}</div>
              <div class="order-number">订单编号: {{ scope.row.orderId }}</div>
            </div>
            <div class="product-detail">
              <div class="product-name">{{ scope.row.goodsName }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="退款状态" align="center" width="150">
        <template slot-scope="scope">
          <div class="status-container">
            <el-button
              :type="getRefundButtonType(scope.row.refundStatus)"
              :class="getRefundButtonClass(scope.row.refundStatus)"
              size="mini"
              disabled
            >
              {{ getRefundButtonText(scope.row.refundStatus) }}
            </el-button>
            <div class="status-dot" :class="getStatusDotClass(scope.row.refundStatus)"></div>
            <span class="status-text">{{ getStatusText(scope.row.refundStatus) }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="退款金额" align="center" prop="refundAmount">
        <template slot-scope="scope">
          <span class="refund-amount">¥{{ scope.row.refundAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewDetail(scope.row)"
          >查看详情</el-button>
          <template v-if="scope.row.refundStatus === 'pending'">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="handleApproveRefund(scope.row)"
              v-hasPermi="['tuikuanguanli:tuikuanguanli:edit']"
            >同意退款</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-close"
              @click="handleRejectRefund(scope.row)"
              v-hasPermi="['tuikuanguanli:tuikuanguanli:edit']"
            >拒绝退款</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 退款详情对话框 -->
    <el-dialog title="退款申请" :visible.sync="detailOpen" width="800px" append-to-body>
      <div class="refund-detail">
        <!-- 退款状态和操作 -->
        <div class="refund-status-section">
          <div class="status-title">{{ getDetailStatusTitle() }}</div>
          <div class="timeout-info" v-if="detailData.refundStatus === 'pending'">
            请在6天12小时34分钟56秒内处理完成，超时自动同意
          </div>
          <div class="action-buttons" v-if="detailData.refundStatus === 'pending'">
            <el-button type="primary" @click="handleApproveRefund(detailData)">同意退款</el-button>
            <el-button type="danger" @click="handleRejectRefund(detailData)">拒绝退款</el-button>
          </div>
        </div>

        <!-- 退款流程步骤 -->
        <div class="refund-steps">
          <el-steps :active="getStepActive()" align-center>
            <el-step title="买家申请退款" :description="detailData.createTime ? parseTime(detailData.createTime, '{y}-{m}-{d} {h}:{i}:{s}') : ''" />
            <el-step title="商户审核" :description="getReviewTime()" />
            <el-step title="退款完成" :description="getCompleteTime()" />
          </el-steps>
        </div>

        <!-- 信息卡片 -->
        <div class="info-cards">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card class="info-card">
                <div slot="header">退款信息</div>
                <div class="info-item">
                  <span class="label">售后类型:</span>
                  <span class="value">退款</span>
                </div>
                <div class="info-item">
                  <span class="label">退款原因:</span>
                  <span class="value">{{ detailData.refundReason || '其他' }}</span>
                  <el-link type="primary" size="mini" v-if="detailData.refundReason">详情</el-link>
                </div>
                <div class="info-item">
                  <span class="label">退款金额:</span>
                  <span class="value amount">¥{{ detailData.refundAmount }}</span>
                </div>
                <div class="info-item">
                  <span class="label">申请时间:</span>
                  <span class="value">{{ parseTime(detailData.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                </div>
                <div class="info-item">
                  <span class="label">超时时间:</span>
                  <span class="value">{{ getTimeoutDate() }}</span>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="info-card">
                <div slot="header">支付信息</div>
                <div class="info-item">
                  <span class="label">订单编号:</span>
                  <span class="value">{{ detailData.orderId }}</span>
                </div>
                <div class="info-item">
                  <span class="label">付款时间:</span>
                  <span class="value">{{ getPaymentTime() }}</span>
                </div>
                <div class="info-item">
                  <span class="label">活动优惠:</span>
                  <span class="value">¥0.00</span>
                </div>
                <div class="info-item">
                  <span class="label">运费:</span>
                  <span class="value">¥0.00</span>
                </div>
                <div class="info-item">
                  <span class="label">付款金额:</span>
                  <span class="value amount">¥{{ detailData.refundAmount }}</span>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="info-card">
                <div slot="header">买家信息</div>
                <div class="info-item">
                  <span class="label">买家昵称:</span>
                  <span class="value">蔡徐坤</span>
                </div>
                <div class="info-item">
                  <span class="label">联系电话:</span>
                  <span class="value">15925656566</span>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 商品列表 -->
        <div class="product-list">
          <el-table :data="productList" border>
            <el-table-column label="商品" width="300">
              <template slot-scope="scope">
                <div class="product-row">
                  <span class="product-name">{{ scope.row.goodsName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="价格" prop="goodsPrice" width="120">
              <template slot-scope="scope">
                <span>¥{{ scope.row.goodsPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="goodsQuantity" width="80" align="center" />
            <el-table-column label="商品状态" prop="goodsStatus" width="120" align="center">
              <template slot-scope="scope">
                <el-tag :type="getGoodsStatusType(scope.row.goodsStatus)">
                  {{ getGoodsStatusText(scope.row.goodsStatus) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTuikuanguanli,
  getTuikuanguanli,
  delTuikuanguanli,
  addTuikuanguanli,
  updateTuikuanguanli,
  approveRefund,
  rejectRefund,
  refundStatusMap
} from "@/api/tuikuanguanli/tuikuanguanli"

export default {
  name: "Tuikuanguanli",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 退款管理表格数据
      refundList: [],
      // 当前激活的状态标签
      activeStatus: 'all',
      // 详情对话框
      detailOpen: false,
      detailData: {},
      productList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        refundNumber: null,
        refundType: null,
        applicationTime: null,
        orderId: null,
        goodsName: null,
        refundStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "订单编号不能为空", trigger: "blur" }
        ],
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        refundAmount: [
          { required: true, message: "退款金额不能为空", trigger: "blur" }
        ],
        refundStatus: [
          { required: true, message: "退款状态不能为空", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询退款管理列表 */
    getList() {
      this.loading = true
      // 根据状态标签设置查询参数
      if (this.activeStatus !== 'all') {
        this.queryParams.refundStatus = this.getStatusValue(this.activeStatus)
      } else {
        this.queryParams.refundStatus = null
      }

      listTuikuanguanli(this.queryParams).then(response => {
        this.refundList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      })
    },
    /** 状态标签切换 */
    handleStatusChange(tab) {
      this.activeStatus = tab.name
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 获取状态值 */
    getStatusValue(status) {
      const statusMap = {
        'pending': 'pending',
        'returning': 'returning',
        'refunding': 'refunding',
        'cancelled': 'cancelled',
        'rejected': 'rejected',
        'refunded': 'refunded'
      }
      return statusMap[status] || null
    },
    /** 获取退款按钮类型 */
    getRefundButtonType(status) {
      const typeMap = {
        'pending': 'primary',
        'returning': 'warning',
        'refunding': 'info',
        'cancelled': 'info',
        'rejected': 'danger',
        'refunded': 'success'
      }
      return typeMap[status] || 'info'
    },
    /** 获取退款按钮样式 */
    getRefundButtonClass(status) {
      return `refund-button-${status}`
    },
    /** 获取退款按钮文本 */
    getRefundButtonText(status) {
      const textMap = {
        'pending': '退款',
        'returning': '退款退货',
        'refunding': '退款中',
        'cancelled': '已取消',
        'rejected': '已拒绝',
        'refunded': '已退款'
      }
      return textMap[status] || '未知'
    },
    /** 获取状态点样式 */
    getStatusDotClass(status) {
      const classMap = {
        'pending': 'status-dot-blue',
        'returning': 'status-dot-orange',
        'refunding': 'status-dot-blue',
        'cancelled': 'status-dot-gray',
        'rejected': 'status-dot-red',
        'refunded': 'status-dot-green'
      }
      return classMap[status] || 'status-dot-gray'
    },
    /** 获取状态文本 */
    getStatusText(status) {
      const textMap = {
        'pending': '待处理',
        'returning': '退货中',
        'refunding': '退款中',
        'cancelled': '已取消',
        'rejected': '已拒绝',
        'refunded': '已退款'
      }
      return textMap[status] || '未知'
    },
    /** 查看详情 */
    handleViewDetail(row) {
      this.detailData = { ...row }
      this.productList = [{
        goodsName: row.goodsName,
        goodsPrice: row.refundAmount,
        goodsQuantity: 1,
        goodsStatus: 'unshipped'
      }]
      this.detailOpen = true
    },
    /** 同意退款 */
    handleApproveRefund(row) {
      this.$modal.confirm('确认同意退款申请吗？').then(() => {
        approveRefund(row.id).then(response => {
          this.$modal.msgSuccess('退款申请已同意')
          this.getList()
          this.detailOpen = false
        })
      })
    },
    /** 拒绝退款 */
    handleRejectRefund(row) {
      this.$prompt('请输入拒绝原因', '拒绝退款', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '拒绝原因不能为空'
      }).then(({ value }) => {
        rejectRefund(row.id, value).then(response => {
          this.$modal.msgSuccess('退款申请已拒绝')
          this.getList()
          this.detailOpen = false
        })
      })
    },
    /** 获取详情状态标题 */
    getDetailStatusTitle() {
      if (this.detailData.refundStatus === 'pending') {
        return '等待处理退款申请'
      }
      return this.getStatusText(this.detailData.refundStatus)
    },
    /** 获取超时文本 */
    getTimeoutText() {
      return '6天12小时34分钟56秒'
    },
    /** 获取步骤激活状态 */
    getStepActive() {
      const statusMap = {
        'pending': 0,
        'returning': 1,
        'refunding': 1,
        'cancelled': 2,
        'rejected': 2,
        'refunded': 2
      }
      return statusMap[this.detailData.refundStatus] || 0
    },
    /** 获取审核时间 */
    getReviewTime() {
      if (['refunding', 'refunded', 'rejected'].includes(this.detailData.refundStatus)) {
        return this.parseTime(this.detailData.updateTime, '{y}-{m}-{d} {h}:{i}:{s}')
      }
      return ''
    },
    /** 获取完成时间 */
    getCompleteTime() {
      if (this.detailData.refundStatus === 'refunded') {
        return this.parseTime(this.detailData.updateTime, '{y}-{m}-{d} {h}:{i}:{s}')
      }
      return ''
    },
    /** 获取超时日期 */
    getTimeoutDate() {
      if (this.detailData.createTime) {
        const createTime = new Date(this.detailData.createTime)
        const timeoutTime = new Date(createTime.getTime() + 7 * 24 * 60 * 60 * 1000)
        return this.parseTime(timeoutTime, '{y}-{m}-{d} {h}:{i}:{s}')
      }
      return ''
    },
    /** 获取支付时间 */
    getPaymentTime() {
      return this.parseTime(this.detailData.createTime, '{y}-{m}-{d} {h}:{i}:{s}')
    },
    /** 获取商品状态类型 */
    getGoodsStatusType(status) {
      const typeMap = {
        'unshipped': 'info',
        'shipped': 'success',
        'delivered': 'success',
        'returned': 'warning'
      }
      return typeMap[status] || 'info'
    },
    /** 获取商品状态文本 */
    getGoodsStatusText(status) {
      const textMap = {
        'unshipped': '未发货',
        'shipped': '已发货',
        'delivered': '已送达',
        'returned': '已退货'
      }
      return textMap[status] || '未知'
    },
    // 取消按钮
    cancel() {
      this.detailOpen = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        goodsName: null,
        refundAmount: null,
        refundReason: null,
        refundStatus: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.activeStatus = 'all'
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('tuikuanguanli/tuikuanguanli/export', {
        ...this.queryParams
      }, `tuikuanguanli_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.status-tabs {
  margin-bottom: 20px;
}

.product-info {
  display: flex;
  align-items: center;
}

.refund-info {
  margin-right: 10px;
  font-size: 12px;
  color: #666;
}

.refund-number, .order-number {
  margin-bottom: 4px;
}

.product-detail {
  display: flex;
  align-items: center;
}

.product-name {
  font-size: 14px;
  color: #333;
}

.status-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin: 4px 0;
}

.status-dot-blue { background-color: #409EFF; }
.status-dot-orange { background-color: #E6A23C; }
.status-dot-green { background-color: #67C23A; }
.status-dot-red { background-color: #F56C6C; }
.status-dot-gray { background-color: #909399; }

.status-text {
  font-size: 12px;
  color: #666;
}

.refund-amount {
  font-weight: bold;
  color: #E6A23C;
}

.refund-detail {
  padding: 20px;
}

.refund-status-section {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.status-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.timeout-info {
  color: #E6A23C;
  margin-bottom: 20px;
}

.action-buttons {
  margin-top: 20px;
}

.refund-steps {
  margin-bottom: 30px;
}

.info-cards {
  margin-bottom: 30px;
}

.info-card {
  height: 100%;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 5px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  color: #666;
  font-size: 14px;
}

.value {
  color: #333;
  font-size: 14px;
}

.value.amount {
  color: #E6A23C;
  font-weight: bold;
}

.product-list {
  margin-top: 20px;
}

.product-row {
  display: flex;
  align-items: center;
}

.product-name {
  font-size: 14px;
  color: #333;
}
</style>
